package com.blt.govdata.controller;

import com.alibaba.fastjson.JSON;
import com.blt.govdata.controller.base.BaseController;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 上传文件管理前端控制器
 * </p>
 * @author AustinGJ123
 * @since 2018-03-26
 */

@RestController
@RequestMapping("/upload")
@CrossOrigin
@MultipartConfig(maxRequestSize = 1024L * 100000)
public class UploadController extends BaseController {
    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;

    @Value("${prop.access-address}")
    private String ACCESS_ADDRESS;

    private Logger logger = LoggerFactory.getLogger(UploadController.class);

    @PostMapping("/file")
    public Map<String, Object> singleFileUpload(MultipartFile file) {
        logger.debug("传入的文件参数：{}", JSON.toJSONString(file, true));
        Map<String,Object> result = Maps.newHashMap();
        if (Objects.isNull(file) || file.isEmpty()) {
            logger.error("文件为空");
            return ImmutableMap.of("status", "false", "msg", "文件为空");
        }

        try {
            byte[] bytes = file.getBytes();
            String fileName = file.getOriginalFilename();
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);//后缀名
            String nowStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            Path path = Paths.get(UPLOAD_FOLDER + nowStr + "/" + fileName);
            //如果没有files文件夹，则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(UPLOAD_FOLDER+ nowStr + "/"));
            }
            //文件写入指定路径
            result.put("fileAdrress",ACCESS_ADDRESS + nowStr +"/"+ fileName);
            result.put("fileName",fileName);
            result.put("fileSize",file.getSize());
            result.put("createTime",BeanUtils.instantiate(Date.class));
            result.put("fileSuffix",fileSuffix);
            Files.write(path, bytes);
            logger.debug("文件写入成功...");
            return ImmutableMap.of("status", "true", "msg", result);
        } catch (IOException e) {
            e.printStackTrace();
            return ImmutableMap.of("status", "false", "msg", e.getMessage());
        }
    }
}